package com.backend.springboot_project_demo.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;

public class JwtUtils {
    public static final Long JWT_EXPIRATION_TIME = 60 * 60 * 1000L;

    public static final String JWT_KEY = "demo";

    public static Claims parseJWT(String jwt) throws Exception {
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }

    public static String crateJwt(String data) {
        return getJwtBuilder(data, null, UuidUtils.getUUID()).compact();
    }

    public static String crateJwt(String data, Long expirationTime) {
        return getJwtBuilder(data, expirationTime, UuidUtils.getUUID()).compact();
    }

    public static String crateJwt(String data, Long expirationTime, String id) {
        return getJwtBuilder(data, expirationTime, id).compact();
    }

    public static SecretKey generalKey() {
        byte[] encodedKey = Base64.getDecoder().decode(JWT_KEY);
        return new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
    }

    private static JwtBuilder getJwtBuilder(String subject, Long expirationTime, String uuid) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        SecretKey secretKey = generalKey();
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        if (expirationTime == null) {
            expirationTime = JWT_EXPIRATION_TIME;
        }
        long expMillis = nowMillis + expirationTime;
        Date expDate = new Date(expMillis);
        return Jwts.builder()
                .setId(uuid)              //唯一的ID
                .setSubject(subject)   // 主题  可以是JSON数据
                .setIssuer("sg")     // 签发者
                .setIssuedAt(now)      // 签发时间
                .signWith(signatureAlgorithm, secretKey) //使用HS256对称加密算法签名, 第二个参数为秘钥
                .setExpiration(expDate);
    }
}
